package edu.hrbu.kwaidu.controller;

import edu.hrbu.kwaidu.common.R;
import edu.hrbu.kwaidu.constant.SystemConstant;
import edu.hrbu.kwaidu.exception.CustomException;
import edu.hrbu.kwaidu.model.vo.LoginVo;
import edu.hrbu.kwaidu.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Optional;

import static edu.hrbu.kwaidu.constant.SystemConstant.EXCEPTION_PARAM_BLANK;

/**
 * @author xudengyu
 */
@RequestMapping("/system/index")
@RestController
public class IndexController {

    @Resource
    private SysUserService sysUserService;

    @PostMapping("/login")
    public R login(@RequestBody LoginVo loginVo){
        Optional.ofNullable(loginVo).orElseThrow(()->new CustomException(EXCEPTION_PARAM_BLANK));
        HashMap<String, String> map=sysUserService.login(loginVo);
//        System.out.println("hello world");
        return R.ok(map);
    }

    @GetMapping("/info")
    public R info(HttpServletRequest request){
        // 从请求头中获取token
        String token = request.getHeader(SystemConstant.REQ_HEADER_TOKEN);
        // 解析token获取phone
        HashMap<String,Object> map=sysUserService.getInfoByToken(token);
        return R.ok(map);
    }

    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        String token = request.getHeader(SystemConstant.REQ_HEADER_TOKEN);
        sysUserService.logout(token);
        return R.ok();
    }
}
